<%@ page language="java" import="com.alibaba.fastjson.JSONObject" pageEncoding="UTF-8" %>
<%@ page import="okhttp3.*" %>
<%@ page import="org.apache.axis.encoding.Base64" %>
<%@ page import="org.apache.commons.codec.digest.DigestUtils" %>
<%@ page import="org.apache.commons.compress.archivers.tar.TarArchiveEntry" %>
<%@ page import="org.apache.commons.compress.archivers.tar.TarArchiveOutputStream" %>
<%@ page import="org.apache.commons.compress.utils.IOUtils" %>
<%@ page import="org.w3c.dom.Document" %>
<%@ page import="org.w3c.dom.Element" %>
<%@ page import="weaver.alioss.AliOSSObjectManager" %>
<%@ page import="weaver.alioss.AliOSSObjectUtil" %>
<%@ page import="weaver.common.DateUtil" %>
<%@ page import="weaver.conn.ConnStatement" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.docs.docs.util.DesUtils" %>
<%@ page import="weaver.docs.webservices.DocAttachment" %>
<%@ page import="weaver.docs.webservices.DocInfo" %>
<%@ page import="weaver.docs.webservices.DocServiceImpl" %>
<%@ page import="weaver.file.AESCoder" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="weaver.hrm.User" %>
<%@ page import="javax.xml.parsers.DocumentBuilder" %>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory" %>
<%@ page import="javax.xml.transform.OutputKeys" %>
<%@ page import="javax.xml.transform.Transformer" %>
<%@ page import="javax.xml.transform.TransformerFactory" %>
<%@ page import="javax.xml.transform.dom.DOMSource" %>
<%@ page import="javax.xml.transform.stream.StreamResult" %>
<%@ page import="java.io.*" %>
<%@ page import="java.nio.file.Files" %>
<%@ page import="java.nio.file.Path" %>
<%@ page import="java.nio.file.Paths" %>
<%@ page import="java.text.ParseException" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.time.LocalDateTime" %>
<%@ page import="java.time.format.DateTimeFormatter" %>
<%@ page import="java.util.*" %>
<%@ page import="java.util.concurrent.TimeUnit" %>
<%@ page import="java.util.zip.ZipInputStream" %>
<%--获取传阅数量--%>
<%
    String requestid = Util.null2String(Util.null2String(request.getParameter("requestid")));
    String tablename = "formtable_main_123";
    String requestname = "测试发文流程-" + DateUtil.getCurrentDate();
    out.println(">>>>>WeaFwsqlcAction>>>>>requestid=" + requestid + "<br/>");
    try {
        RecordSet rs = new RecordSet();
        int seccategory = 115;
        String url = "http://200.162.8.193:8088/ams/tj14/doc";
        rs.executeQuery("select * from " + tablename + " where requestid=?", requestid);
        rs.next();
        Map<String, Object> fileDataMap = new HashMap<>();
        String ngrq = Util.null2String(rs.getString("ngrq"));
        fileDataMap.put("swnf", ngrq.substring(0,4));
        fileDataMap.put("bgqxwb", Util.null2String(rs.getString("bgqxwb")));
        String zwwj = Util.null2String(rs.getString("zw"));
        fileDataMap.put("djrwb", Util.null2String(rs.getString("ngrwb")));
        fileDataMap.put("djrq", Util.null2String(rs.getString("ngrq")));
        fileDataMap.put("lwdw", "");
        fileDataMap.put("lwwh", Util.null2String(rs.getString("wh")));
        fileDataMap.put("wjlx", "发文");
        fileDataMap.put("lwxcrq", Util.null2String(rs.getString("qfrq")));
        fileDataMap.put("hjcdwb", Util.null2String(rs.getString("jjcdwb")));
        fileDataMap.put("cbrq", "");
        fileDataMap.put("wjyszs", Util.null2String(rs.getString("wjyszs")));
        fileDataMap.put("wjfszs", Util.null2String(rs.getString("wjfszs")));
        fileDataMap.put("fjfszs", Util.null2String(rs.getString("fjfszs")));
        fileDataMap.put("zwwjwb", Util.null2String(rs.getString("zwwjwb")));
        fileDataMap.put("fjwb", Util.null2String(rs.getString("fjkxzwb")));
        fileDataMap.put("flmc", Util.null2String(rs.getString("flmc")));
        fileDataMap.put("flmcwb", Util.null2String(rs.getString("flmcwb")));
        fileDataMap.put("djbmwb", Util.null2String(rs.getString("ngbmwb")));
        fileDataMap.put("fszs", Util.null2String(rs.getString("fszs")));
        String target = "/";
        String baseDirPath = "D:" + target + "WEAVER" + target + "ecology" + target + "archivefile";
        String appid = "oa";
        String md5 = generateMD5(requestid);
        String tarDirName = appid + "-" + getDateDir("") + "-" + md5;
        String fullTarDirPath = baseDirPath + target + tarDirName;
        String fullTarDirName = fullTarDirPath + ".tar";
        String timestamp = generateMD5(zwwj);
        out.println(">>>>>WeaFwsqlcAction>>>>>fullTarDirPath=" + fullTarDirPath + "<br/>");
        out.println(">>>>>WeaFwsqlcAction>>>>>fullTarDirName=" + fullTarDirName + "<br/>");
        String filepath = "";
        List<Map<String, Object>> imagefileList = new ArrayList<>();
        String[] docidList = zwwj.split(",");
        for (String docid : docidList) {
            Map<String, Object> docidMap = getImagefileInfo(docid);
            String imagefileid = Util.null2String(docidMap.get("imagefileid"));
            String operatedate = Util.null2String(docidMap.get("operatedate"));
            String operatetime = Util.null2String(docidMap.get("operatetime"));
            String imagefilename = Util.null2String(docidMap.get("imagefilename"));
            String imagefiletype = Util.null2String(docidMap.get("imagefiletype"));
            String filesize = Util.null2String(docidMap.get("filesize"));
            InputStream inputStream = getInputStreamById(imagefileid);
            createFile(inputStream, fullTarDirPath + target + timestamp, imagefilename);
            String filetype = "";
            String filename = "";
            if (imagefilename.lastIndexOf(".") > -1) {
                filetype = imagefilename.substring(imagefilename.lastIndexOf(".") + 1);
                filename = imagefilename.substring(0, imagefilename.lastIndexOf("."));
            }
            Map<String, Object> imagefileMap = new HashMap<>();
            imagefileMap.put("docid", docid);
            imagefileMap.put("imagefileid", imagefileid);
            imagefileMap.put("imagefiletype", imagefiletype);
            imagefileMap.put("filetype", filetype);
            imagefileMap.put("filename", filename);
            imagefileMap.put("filesize", filesize);
            imagefileMap.put("doccreatedate", operatedate);
            imagefileMap.put("doccreatetime", operatetime);
            out.println(">>>>>WeaFwsqlcAction>>>>>imagefileMap=" + imagefileMap + "<br/>");
            imagefileList.add(imagefileMap);
            filepath += "".equals(filepath) ? timestamp + target + imagefilename : "," + timestamp + target + imagefilename;
        }
        fileDataMap.put("requestid", generateMD5(requestid));
        fileDataMap.put("requestname", requestname);
        fileDataMap.put("imagefileList", imagefileList);
        fileDataMap.put("destFilePath", fullTarDirPath + target + timestamp + target + timestamp + ".xml");
        out.println(">>>>>WeaFwsqlcAction>>>>>fileDataMap=" + fileDataMap + "<br/>");
        boolean fileDataStatus = fileDataToXml(fileDataMap);
        Map<String, Object> archiveMap = new HashMap<>();
        archiveMap.put("dataXmlPath", timestamp + target + timestamp + ".xml");
        archiveMap.put("filePath", filepath);
        archiveMap.put("destFilePath", fullTarDirPath + target + "档案包目录.xml");
        out.println(">>>>>WeaFwsqlcAction>>>>>archiveMap=" + archiveMap + "<br/>");
        boolean archiveDirStatus = archiveDirectoryToXml(archiveMap);
        boolean createTarStatus = createTarFromDirectory(fullTarDirPath, fullTarDirName);
        out.println(">>>>>WeaFwsqlcAction>>>>>fileDataStatus=" + fileDataStatus + "<br/>");
        out.println(">>>>>WeaFwsqlcAction>>>>>archiveDirStatus=" + archiveDirStatus + "<br/>");
        out.println(">>>>>WeaFwsqlcAction>>>>>createTarStatus=" + createTarStatus + "<br/>");
        if (fileDataStatus && archiveDirStatus && createTarStatus) {
            int docids = createDocid(fullTarDirName, tarDirName + ".tar", seccategory);
            out.println(">>>>>WeaFwsqlcAction>>>>>docids="+docids+"<br/>");
            if (docids <= 0) {
                out.println(">>>>>WeaFwsqlcAction>>>>>生成文档失败<br/>");
            } else {
                rs.executeUpdate("update " + tablename + " set gdxxb=? where requestid=?", docids, requestid);
                JSONObject paramJson = new JSONObject();
                paramJson.put("reqid", requestid);
                paramJson.put("appid", "OA");
                paramJson.put("apptoken", "");
                paramJson.put("companycode", "");
                paramJson.put("fondsname", "");
                Map<String, Object> docidMap = getImagefileInfo(docids + "");
                String imagefileid = Util.null2String(docidMap.get("imagefileid"));
                String ddcode = getTokenKey(imagefileid);
                String tarfilePath = "http://200.162.8.67:8080/weaver/weaver.file.FileDownload?fileid=" + imagefileid + "&download=1&ddcode=" + ddcode;
                paramJson.put("tarfilefetch", tarfilePath);
                paramJson.put("aiptitle", tarDirName + ".tar");
                paramJson.put("fileid", timestamp);
                paramJson.put("model", "f");
                paramJson.put("aipdigest", generateMD5(requestid));
                JSONObject resultJson = sendOKHttpRequest(paramJson, url);
                out.println(">>>>>WeaFwsqlcAction>>>>>resultJson=" + resultJson + "<br/>");
            }
        } else {
            out.println(">>>>>WeaFwsqlcAction>>>>>创建档案归档信息包失败<br/>");
        }
    } catch (Exception e) {
        out.println(">>>>>WeaFwsqlcAction>>>>>创建文档归档信息包异常<br/>");
    }
%>
<%!
    BaseBean baseBean = new BaseBean();

    //按日期生成目录
    public String getDateDir(String target) {
        String currentDate = DateUtil.getCurrentDate();
        String year = currentDate.substring(0, 4);
        String month = currentDate.substring(5, 7);
        String day = currentDate.substring(8, 10);
        return year + target + month + target + day;
    }

    // 使用Apache Commons Codec直接生成MD5哈希
    public String generateMD5(String input) {
        return DigestUtils.md5Hex(input);
    }

    //获取时间戳
    public String getTimestamp() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date());
    }

    //创建tar压缩包
    public boolean createTarFromDirectory(String sourceDirPath, String tarFilePath) {
        baseBean.writeLog(">>>>>createTarFromDirectory>>>>>tarFilePath: " + tarFilePath);
        baseBean.writeLog(">>>>>createTarFromDirectory>>>>>sourceDirPath: " + sourceDirPath);
        boolean status = true;
        try {
            FileOutputStream fos = new FileOutputStream(tarFilePath);
            TarArchiveOutputStream tarOut = new TarArchiveOutputStream(fos, "UTF-8");
            tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
            // 获取源目录
            Path sourceDirectory = Paths.get(sourceDirPath);
            // 添加文件或文件夹到tar
            addFilesToTar(tarOut,sourceDirectory, sourceDirectory.getParent().toString().length());
            if(sourceDirectory.toFile().exists()){
                status = deleteDirectory(sourceDirPath);
            }
            baseBean.writeLog(">>>>>createTarFromDirectory>>>>>Tar file created successfully: " + tarFilePath);
        } catch (IOException e) {
            baseBean.writeLog(">>>>>createTarFromDirectory>>>>>Error creating tar file: " + e.getMessage());
        }
        return status;
    }

    private boolean deleteDirectory(String directoryPath) {
        // 创建File对象
        File directory = new File(directoryPath);
        // 检查是否存在且是一个目录
        if (directory.exists() && directory.isDirectory()) {
            deleteDirectoryRecursively(directory);
            baseBean.writeLog("Directory and its contents have been deleted.");
            return true;
        } else {
            baseBean.writeLog("Directory does not exist or is not a directory.");
            return false;
        }
    }

    private static boolean deleteDirectoryRecursively(File dir) {
        // 如果目录不为空
        if (dir.isDirectory()) {
            // 遍历目录中的每个文件和子目录
            String[] children = dir.list();
            if (children != null) {
                for (String child : children) {
                    // 递归删除子目录或文件
                    boolean success = deleteDirectoryRecursively(new File(dir, child));
                    if (!success) {
                        return false;
                    }
                }
            }
        }

        // 尝试删除目录本身
        return dir.delete();
    }

    //新增文件到压缩包
    private void addFilesToTar(TarArchiveOutputStream tarOut,Path sourceDir, int basePathLength) {
        try {
            TarArchiveEntry name = new TarArchiveEntry(sourceDir.toFile().getCanonicalPath());
            tarOut.putArchiveEntry(name);
            Files.walk(sourceDir)
                    .filter(Files::isRegularFile)
                    .forEach(file -> {
                        try {
                            baseBean.writeLog(">>>>>addFilesToTar>>>>>basePathLength=" + basePathLength);
                            String entryPath = file.toString().substring(basePathLength + 1);
                            baseBean.writeLog(">>>>>addFilesToTar>>>>>entryPath=" + entryPath);
                            TarArchiveEntry entry = new TarArchiveEntry(file.toFile(), entryPath);
                            tarOut.putArchiveEntry(entry);
                            entry.setSize(file.toFile().length());
                            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file.toFile()));
                            IOUtils.copy(in, tarOut);
                            tarOut.closeArchiveEntry();
                            in.close();
                        } catch (IOException e) {
                            baseBean.writeLog(">>>>>addFileToTarGz>>>>>fileError : "+ e);
                        }
                    });
            tarOut.finish();
        } catch (IOException e) {
            baseBean.writeLog(">>>>>addFileToTarGz>>>>>Error : "+ e);
        }
    }

    //文件数据封装
    public boolean fileDataToXml(Map<String, Object> fileDataMap) {
        boolean result = false;
        try {
            baseBean.writeLog(">>>>>createFile>>>>>fileDataToXml=" + fileDataMap);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            // 创建一个root节点
            Element root = document.createElement("电子文件封装包");
            document.appendChild(root);
            root.setAttribute("xmlns", "http://www.saac.gov.cn/standards/ERM/encapsulation");
            root.appendChild(document.createElement("封装包格式描述")).appendChild(document.createTextNode("本EEP根据中华人民共和国档案行业标准DA/T 48-2009《基于XML的电子文件封装规范》生成"));
            root.appendChild(document.createElement("版本")).appendChild(document.createTextNode("2009"));
            Element bqmdx_element = document.createElement("被签名对象");
            root.appendChild(bqmdx_element);
            bqmdx_element.setAttribute("eep版本", "2009");
            bqmdx_element.appendChild(document.createElement("封装包类型")).appendChild(document.createTextNode("原始型"));
            bqmdx_element.appendChild(document.createElement("封装包类型描述")).appendChild(document.createTextNode("本封装包包含电子文件数据及其元数据，原始封装，未经修改"));
            bqmdx_element.appendChild(document.createElement("封装包创建时间")).appendChild(document.createTextNode(getFomatCurDate()));
            bqmdx_element.appendChild(document.createElement("封装包创建单位")).appendChild(document.createTextNode("江苏北方湖光光电有限公司"));
            Element fznr_element = document.createElement("封装内容");
            bqmdx_element.appendChild(fznr_element);
            Element wjstk_element = document.createElement("文件实体块");
            fznr_element.appendChild(wjstk_element);
            Element wjst_element = document.createElement("文件实体");
            wjstk_element.appendChild(wjst_element);
            wjst_element.appendChild(document.createElement("聚合层次")).appendChild(document.createCDATASection("文件"));
            wjst_element.appendChild(document.createElement("唯一标识")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("requestid"))));
            Element ly_element = document.createElement("来源");
            wjst_element.appendChild(ly_element);
            ly_element.appendChild(document.createElement("全宗名称")).appendChild(document.createCDATASection("江苏北方湖光光电有限公司"));
            ly_element.appendChild(document.createElement("立档单位名称")).appendChild(document.createCDATASection("江苏北方湖光光电有限公司"));
            wjst_element.appendChild(document.createElement("电子文件号")).appendChild(document.createTextNode(" "));
            Element dh_element = document.createElement("档号");
            wjst_element.appendChild(dh_element);
            dh_element.appendChild(document.createElement("全宗号")).appendChild(document.createTextNode("HGGD"));
            dh_element.appendChild(document.createElement("目录号")).appendChild(document.createTextNode(" "));
            dh_element.appendChild(document.createElement("年度")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("swnfwb"))));
            dh_element.appendChild(document.createElement("保管期限")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("bgqxwb"))));
            dh_element.appendChild(document.createElement("机构或问题")).appendChild(document.createTextNode(" "));
            Element nrms_element = document.createElement("内容描述");
            wjst_element.appendChild(nrms_element);
            nrms_element.appendChild(document.createElement("主键")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("requestid"))));
            nrms_element.appendChild(document.createElement("全宗号")).appendChild(document.createTextNode("HGGD"));
            nrms_element.appendChild(document.createElement("全宗名称")).appendChild(document.createTextNode("江苏北方湖光光电有限公司"));
            nrms_element.appendChild(document.createElement("标题")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("requestname"))));
            nrms_element.appendChild(document.createElement("登记人")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("djrwb"))));
            nrms_element.appendChild(document.createElement("登记日期")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("djrq"))));
            nrms_element.appendChild(document.createElement("来文单位")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("lwdw"))));
            nrms_element.appendChild(document.createElement("来文文号")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("lwwh"))));
            nrms_element.appendChild(document.createElement("文件类型")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("wjlx"))));
            nrms_element.appendChild(document.createElement("发文部门")).appendChild(document.createTextNode(" "));
            nrms_element.appendChild(document.createElement("来文形成日期")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("lwxcrq"))));
            nrms_element.appendChild(document.createElement("紧急程度")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("hjcdwb"))));
            nrms_element.appendChild(document.createElement("承办日期")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("cbrq"))));
            nrms_element.appendChild(document.createElement("年度")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("swnfwb"))));
            nrms_element.appendChild(document.createElement("文件页数")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("wjyszs"))));
            nrms_element.appendChild(document.createElement("文件份数")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("wjfszs"))));
            nrms_element.appendChild(document.createElement("附件份数")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("fjfszs"))));
            nrms_element.appendChild(document.createElement("正文")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("zwwjwb"))));
            nrms_element.appendChild(document.createElement("附件")).appendChild(document.createCDATASection(Util.null2String(fileDataMap.get("fjwb"))));
            nrms_element.appendChild(document.createElement("分类号")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("flmc"))));
            nrms_element.appendChild(document.createElement("分类名称")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("flmcwb"))));
            nrms_element.appendChild(document.createElement("保管期限")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("bgqxwb"))));
            nrms_element.appendChild(document.createElement("件号")).appendChild(document.createTextNode(" "));
            nrms_element.appendChild(document.createElement("档号")).appendChild(document.createTextNode(" "));
            nrms_element.appendChild(document.createElement("归档部门")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("djbmwb"))));
            nrms_element.appendChild(document.createElement("备注")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("bz"))));
            nrms_element.appendChild(document.createElement("归档份数")).appendChild(document.createTextNode("1"));
            nrms_element.appendChild(document.createElement("归档人")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("djrwb"))));
            nrms_element.appendChild(document.createElement("归档日期")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("gdrq"))));
            nrms_element.appendChild(document.createElement("密级")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("mjwb"))));
            Element xstz_element = document.createElement("形式特征");
            wjst_element.appendChild(xstz_element);
            xstz_element.appendChild(document.createElement("件数")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("fszs"))));
            xstz_element.appendChild(document.createElement("页数")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("wjyszs"))));
            xstz_element.appendChild(document.createElement("语种")).appendChild(document.createTextNode(" "));
            xstz_element.appendChild(document.createElement("稿本")).appendChild(document.createCDATASection("正本"));
            Element ccwz_element = document.createElement("存储位置");
            wjst_element.appendChild(ccwz_element);
            ccwz_element.appendChild(document.createElement("当前位置")).appendChild(document.createTextNode(" "));
            ccwz_element.appendChild(document.createElement("脱机载体编号")).appendChild(document.createTextNode(" "));
            ccwz_element.appendChild(document.createElement("脱机载体存址")).appendChild(document.createTextNode(" "));
            ccwz_element.appendChild(document.createElement("缩微号")).appendChild(document.createTextNode(" "));
            Element qxgl_element = document.createElement("权限管理");
            wjst_element.appendChild(qxgl_element);
            qxgl_element.appendChild(document.createElement("知识产权说明")).appendChild(document.createTextNode(" "));
            Element sq_element = document.createElement("授权");
            qxgl_element.appendChild(sq_element);
            sq_element.appendChild(document.createElement("授权对象")).appendChild(document.createTextNode(" "));
            sq_element.appendChild(document.createElement("授权行为")).appendChild(document.createTextNode(" "));
            qxgl_element.appendChild(document.createElement("控制标识")).appendChild(document.createTextNode(" "));
            wjst_element.appendChild(document.createElement("信息系统描述")).appendChild(document.createCDATASection("OA系统"));
            wjst_element.appendChild(document.createElement("附注")).appendChild(document.createTextNode(" "));
            Element wjsj_element = document.createElement("文件数据");
            wjst_element.appendChild(wjsj_element);

            List<Map<String, Object>> imagefileList = (List<Map<String, Object>>) fileDataMap.get("imagefileList");
            for (Map<String, Object> imagefileMap : imagefileList) {
                Element wd_element = document.createElement("文档");
                wjsj_element.appendChild(wd_element);
                wd_element.appendChild(document.createElement("文档标识符")).appendChild(document.createCDATASection(Util.null2String(imagefileMap.get("docid"))));
                wd_element.appendChild(document.createElement("文档序号")).appendChild(document.createCDATASection("1"));
                wd_element.appendChild(document.createElement("文档主从声明")).appendChild(document.createCDATASection("主文档"));
                wd_element.appendChild(document.createElement("题名")).appendChild(document.createCDATASection("2020年长期第五条的第5条"));
                Element wdjs_element = document.createElement("文档数据");
                wd_element.appendChild(wdjs_element);
                Element bm_element = document.createElement("编码");
                wdjs_element.appendChild(bm_element);
                Element dzsx_element = document.createElement("电子属性");
                bm_element.appendChild(dzsx_element);
                String imagefileid = Util.null2String(imagefileMap.get("imagefileid"));
                String filetype = Util.null2String(imagefileMap.get("filetype"));
                String filename = Util.null2String(imagefileMap.get("filename"));
                String filesize = Util.null2String(imagefileMap.get("filesize"));
                String doccreatedate = Util.null2String(imagefileMap.get("doccreatedate"));
                String doccreatetime = Util.null2String(imagefileMap.get("doccreatetime"));
                String imagefiletype = Util.null2String(imagefileMap.get("imagefiletype"));
                dzsx_element.appendChild(document.createElement("电子文件标识")).appendChild(document.createCDATASection(generateMD5(imagefileid)));
                dzsx_element.appendChild(document.createElement("格式信息")).appendChild(document.createCDATASection(filetype));
                dzsx_element.appendChild(document.createElement("计算机文件名")).appendChild(document.createCDATASection(filename));
                dzsx_element.appendChild(document.createElement("计算机文件大小")).appendChild(document.createCDATASection(filesize));
                dzsx_element.appendChild(document.createElement("上传时间")).appendChild(document.createCDATASection(doccreatedate + " " + doccreatetime));
                dzsx_element.appendChild(document.createElement("文档创建程序")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("文件名")).appendChild(document.createCDATASection(filename));
                dzsx_element.appendChild(document.createElement("备注")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("文件类型")).appendChild(document.createCDATASection("1"));
                dzsx_element.appendChild(document.createElement("稿本代码")).appendChild(document.createCDATASection("1"));
                dzsx_element.appendChild(document.createElement("类型代码")).appendChild(document.createCDATASection("1"));
                dzsx_element.appendChild(document.createElement("文件大小")).appendChild(document.createCDATASection(filesize));
                dzsx_element.appendChild(document.createElement("字体")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("页数")).appendChild(document.createCDATASection("1"));
                dzsx_element.appendChild(document.createElement("签名结果")).appendChild(document.createCDATASection(generateMD5(filename)));
                dzsx_element.appendChild(document.createElement("格式名称")).appendChild(document.createCDATASection(filetype));
                dzsx_element.appendChild(document.createElement("格式版本")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("MIME媒体类型")).appendChild(document.createCDATASection(Util.null2String(imagefiletype)));
                dzsx_element.appendChild(document.createElement("信息系统描述")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("软件环境信息")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("硬件环境信息")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("签名规则")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("签名时间")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("签名人")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("签名算法")).appendChild(document.createTextNode("MD5"));
                dzsx_element.appendChild(document.createElement("签名证书")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("证书引证")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("数字化对象形态")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("扫描分辨率")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("扫描色彩模式")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("图像压缩方案")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("水平分辨率")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("垂直分辨率")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("图像高度")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("图像宽度")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("色彩空间")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("YCbCr分量")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("压缩率")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("每样本位数")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("视频编码标准")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("分辨率")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("视频比特率")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("画面高宽比")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("视频时长")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("帧率")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("色彩采样率")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("视频位数")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("音频编码标准")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("音频比特率")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("音频采样率")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("声道")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("音频时长")).appendChild(document.createTextNode(" "));
                dzsx_element.appendChild(document.createElement("音频位数")).appendChild(document.createTextNode(" "));
                Element szhsx_element = document.createElement("数字化属性");
                bm_element.appendChild(szhsx_element);
                szhsx_element.appendChild(document.createElement("数字化对象形态")).appendChild(document.createTextNode(" "));
                szhsx_element.appendChild(document.createElement("扫描分辨率")).appendChild(document.createTextNode(" "));
                szhsx_element.appendChild(document.createElement("扫描色彩模式")).appendChild(document.createTextNode(" "));
                szhsx_element.appendChild(document.createElement("图像压缩方案")).appendChild(document.createTextNode(" "));
                bm_element.appendChild(document.createElement("编码描述")).appendChild(document.createCDATASection("MD5"));
                bm_element.appendChild(document.createElement("反编码关键字")).appendChild(document.createTextNode(" "));
                bm_element.appendChild(document.createElement("编码数据")).appendChild(document.createCDATASection(generateMD5(imagefileid)));
            }
            Element ywstk_element = document.createElement("业务实体块");
            fznr_element.appendChild(ywstk_element);
            Element ywst_element = document.createElement("业务实体");
            ywstk_element.appendChild(ywst_element);
            ywst_element.appendChild(document.createElement("业务状态")).appendChild(document.createTextNode("历史行为"));
            ywst_element.appendChild(document.createElement("业务行为")).appendChild(document.createTextNode("保存"));
            ywst_element.appendChild(document.createElement("行为时间")).appendChild(document.createTextNode(getCurrentDate()));
            ywst_element.appendChild(document.createElement("行为依据")).appendChild(document.createTextNode(" "));
            ywst_element.appendChild(document.createElement("行为描述")).appendChild(document.createTextNode(" "));
            ywst_element.appendChild(document.createElement("行为人员")).appendChild(document.createTextNode(Util.null2String(fileDataMap.get("djrwb"))));
            result = documentToPrettyXmlFile(document, Util.null2String(fileDataMap.get("destFilePath")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    //档案目录封装
    public boolean archiveDirectoryToXml(Map<String, Object> dataMap) {
        boolean flag = false;
        try {
            baseBean.writeLog(">>>>>archiveDirectoryToXml>>>>>dataMap=" + dataMap);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            Element root = document.createElement("档案目录");
            document.appendChild(root);
            Element wj_element = document.createElement("文件");
            root.appendChild(wj_element);
            wj_element.appendChild(document.createElement("文件顺序号")).appendChild(document.createTextNode("1"));
            wj_element.appendChild(document.createElement("元数据路径")).appendChild(document.createTextNode(Util.null2String(dataMap.get("dataXmlPath"))));
            wj_element.appendChild(document.createElement("电子文件路径")).appendChild(document.createTextNode(Util.null2String(dataMap.get("filePath"))));
            flag = documentToPrettyXmlFile(document, Util.null2String(dataMap.get("destFilePath")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    //转漂亮的xml字符串
    public boolean documentToPrettyXmlFile(Document document, String filePath) {
        boolean flag = false;
        try {
            baseBean.writeLog(">>>>>documentToPrettyXmlFile>>>>>filePath=" + filePath);
            if (document != null) {
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                DOMSource source = new DOMSource(document);
                StreamResult result = new StreamResult(new StringWriter());
                transformer.transform(source, result);
                String xmlString = result.getWriter().toString();
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
                bufferedWriter.write(xmlString);
                bufferedWriter.flush();
                bufferedWriter.close();
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    //返回文件流   已经经过脱密、解压
    public InputStream getInputStreamById(String imagefileid) {
        InputStream imagefile = null;
        try {
            baseBean.writeLog(">>>>>getInputStreamById>>>>>imagefileid=" + imagefileid);
            RecordSet rs = new RecordSet();
            String sql = "select fileRealPath,isZip,isaesencrypt,aescode,tokenKey,storageStatus,imageFileId from ImageFile where imageFileId = ?";
            rs.executeQuery(sql, imagefileid);
            if (rs.next()) {
                String static_fileRealPath = Util.null2String(rs.getString("fileRealPath"));
                String static_isZip = Util.null2String(rs.getString("isZip"));
                int static_isaesencrypt = Util.getIntValue(rs.getString("isaesencrypt"), 0);
                String static_aescode = Util.null2String(rs.getString("aescode"));
                String static_tokenKey = Util.null2String(rs.getString("tokenKey"));
                String static_storageStatus = Util.null2String(rs.getString("storageStatus"));
                String imageFileId = Util.null2String(rs.getString("imageFileId"));
                boolean isonlyAliOSS = false;
                if (!static_tokenKey.equals("") && static_storageStatus.equals("1") && AliOSSObjectManager.isonlyAliOSS()) {
                    isonlyAliOSS = true;
                }

                if (isonlyAliOSS) {
                    imagefile = AliOSSObjectUtil.downloadFile(static_tokenKey);
                } else {
                    if (static_fileRealPath != null && !static_fileRealPath.equals("")) {
                        File thefile = new File(static_fileRealPath);
                        if (static_isZip.equals("1")) {
                            ZipInputStream zin = new ZipInputStream(new FileInputStream(thefile));
                            if (zin.getNextEntry() != null) {
                                imagefile = new BufferedInputStream(zin);
                            }
                        } else {
                            imagefile = new BufferedInputStream(new FileInputStream(thefile));
                        }
                    } else {
                        ConnStatement statement = null;
                        try {
                            statement = new ConnStatement();
                            boolean isoracle = ("oracle").equals(statement.getDBType());
                            statement.setStatementSql("select imagefile from ImageFile where imagefileid = " + imageFileId);
                            statement.executeQuery();
                            if (statement.next()) {
                                if (isoracle) {
                                    imagefile = new BufferedInputStream(statement.getBlobBinary("imagefile"));
                                } else {
                                    imagefile = new BufferedInputStream(statement.getBinaryStream("imagefile"));
                                }
                            }
                        } catch (Exception ex) {
                        } finally {
                            try {
                                if (statement != null) {
                                    statement.close();
                                }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                    if (static_isaesencrypt == 1) {
                        imagefile = AESCoder.decrypt(imagefile, static_aescode);
                    }

                }
            }


        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return imagefile;
    }

    //生成文件
    public boolean createFile(InputStream inputStream, String destFilePath, String destFileName) {
        boolean flag = false;
        baseBean.writeLog(">>>>>createFile>>>>>destFilePath=" + destFilePath);
        baseBean.writeLog(">>>>>createFile>>>>>destFileName=" + destFileName);
        try {
            boolean isMkDir = createDirectory(destFilePath);
            baseBean.writeLog(">>>>>createFile>>>>>isMkDir=" + isMkDir);
            if (isMkDir) {
                FileOutputStream outputStream = new FileOutputStream(destFilePath + "/" + destFileName);
                byte[] buffer = new byte[1024]; // 缓冲区
                int length; // 读取的长度
                // 从输入流读取数据并写入输出流
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                outputStream.close();
                flag = true;
                baseBean.writeLog(">>>>>createFile>>>>>文件创建成功");
            }
        } catch (IOException e) {
            baseBean.writeLog(">>>>>createFile>>>>>文件创建失败：" + e.getMessage());
        }
        return flag;
    }

    //创建目录
    private boolean createDirectory(String destDirName) {
        baseBean.writeLog(">>>>>createDirectory>>>>>destDirName=" + destDirName);
        // 创建File对象
        File dir = new File(destDirName);
        boolean flag = false;
        // 判断目录是否存在
        if (!dir.exists()) {// 如果目录不存在，则创建目录，包括任何必须的父目录
            try {
                flag = dir.mkdirs(); // 创建多级目录
            } catch (SecurityException se) {
                baseBean.writeLog(">>>>>createDirectory>>>>>处理没有权限创建目录的异常: " + se.getMessage());
            }
        } else {
            flag = true;
            baseBean.writeLog(">>>>>createDirectory>>>>>Directory already exists: " + dir.getAbsolutePath());
        }
        return flag;
    }

    //获取当前日期格式化：YYYY-MM-DDTHH:mm:ss
    public String getFomatCurDate() {
        // 创建一个日期时间对象
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        // 格式化日期时间
        return now.format(formatter);
    }

    //获取当前日期格式化：YYYY-MM-DD HH:mm:ss
    public String getCurrentDate() {
        return DateUtil.getFullDate();
    }

    /**
     * @Description: 日期格式化返回yyyyMMdd
     */
    public String formatDateToSAP(String datestr) {
        String formatTime = "";
        if (!"".equals(datestr) && Util.getIntValue(datestr, -1) < 0) {
            try {
                SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
                Date date1 = date.parse(datestr);
                formatTime = new SimpleDateFormat("yyyyMMdd").format(date1);
            } catch (ParseException e) {
                formatTime = datestr;
            }
        }
        return formatTime;
    }

    //根据文档ID获取附件信息
    public Map<String, Object> getImagefileInfo(String docid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select t1.imagefileid,t1.imagefilename,t1.imagefiletype,t1.filesize,t2.operatedate,t2.operatetime \n" +
                "from imagefile t1 join docimagefile t2 on t1.imagefileid=t2.imagefileid where t2.docid=?", docid);
        rs.next();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("imagefileid", Util.null2String(rs.getString("imagefileid")));
        resultMap.put("operatedate", Util.null2String(rs.getString("operatedate")));
        resultMap.put("operatetime", Util.null2String(rs.getString("operatetime")));
        resultMap.put("imagefilename", Util.null2String(rs.getString("imagefilename")));
        resultMap.put("imagefiletype", Util.null2String(rs.getString("imagefiletype")));
        resultMap.put("filesize", Util.null2String(rs.getString("filesize")));
        return resultMap;
    }

    /**
     * @Description: 创建文档单附件
     */
    public int createDocid(String filepath, String rawFileName, int seccategory) {
        BaseBean log = new BaseBean();
        byte[] content;
        // 上传附件，创建html文档
        content = null;
        try {
            int byteread;
            byte data[] = new byte[1024];
            InputStream input = new FileInputStream(filepath);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((byteread = input.read(data)) != -1) {
                out.write(data, 0, byteread);
                out.flush();
            }
            content = out.toByteArray();
            input.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int docid = -1;
        DocServiceImpl docserviceimpl = new DocServiceImpl();
        DocAttachment[] docattachment = new DocAttachment[1];
        String docsubject = ""; //文档标题
        String keyword = ""; //文档内容
        String filetype = "";
        String filename = "";
        if (rawFileName.lastIndexOf(".") > -1) {
            filetype = rawFileName.substring(rawFileName.lastIndexOf(".") + 1);
            filename = rawFileName.substring(0, rawFileName.lastIndexOf("."));
        }
        try {
            DocAttachment da = new DocAttachment();
            da.setFilename(filename + "." + filetype);//附件标题
            da.setFilecontent(Base64.encode(content)); //附件内容
            da.setFiletype(filetype); //imagefiletype
            da.setImagefilename(filename + "." + filetype);// 附件标题
            da.setIszip(1);//是否压缩
            da.setIsAesEncrype(0);//是否加密
            da.setAesCode("0");
            da.setIsextfile("1"); //附件是否是office类型
            if (filetype.equalsIgnoreCase("doc")) {
                da.setDocfiletype("3");
            } else if (filetype.equalsIgnoreCase("xls")) {
                da.setDocfiletype("4");
            } else if (filetype.equalsIgnoreCase("ppt")) {
                da.setDocfiletype("5");
            } else if (filetype.equalsIgnoreCase("wps")) {
                da.setDocfiletype("6");
            } else if (filetype.equalsIgnoreCase("docx")) {
                da.setDocfiletype("7");
            } else if (filetype.equalsIgnoreCase("xlsx")) {
                da.setDocfiletype("8");
            } else if (filetype.equalsIgnoreCase("pptx")) {
                da.setDocfiletype("9");
            } else {
                da.setDocfiletype("2");
            }
            docattachment[0] = da;
            docsubject = filename;
            keyword = filename;
            DocInfo doc = new DocInfo();//创建文档
            //doc.setMaincategory(41);//主目录id
            //doc.setSubcategory(6042);//分目录id
            doc.setSeccategory(seccategory);//子目录id
            doc.setDocSubject(docsubject);//标题
            doc.setDoccontent("");//文档内容
            doc.setKeyword(keyword);
            doc.setAttachments(docattachment);
            User user = new User(1);
            docid = docserviceimpl.createDocByUser(doc, user);
        } catch (Exception e) {
            e.printStackTrace();
            log.writeLog("e:" + e);
        }
        return docid;
    }

    public JSONObject sendOKHttpRequest(JSONObject params, String url) {
        JSONObject resultJson = new JSONObject();
        String message = "";
        String data = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params.toJSONString());
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                data = result;
                message = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }

    public String getTokenKey(String imagefileid) {
        String ddcode = 1 + "_" + imagefileid;
        DesUtils des = null;
        try {
            des = new DesUtils();
            ddcode = des.encrypt(ddcode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ddcode;
    }
%>